package com.hehao.java_basic.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * @author Damon
 * @date 2021/12/20
 */
@Slf4j
public class ForkJoin {
    public static void main(String[] args) {
        int sum = 0;
        List<Integer> list = new ArrayList<>();
        IntStream.range(1,10000).forEach(list::add);
        for (Integer i : list) {
            sum += i;
        }
        System.out.println(sum);

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Integer> task = new SumTask(1, 10000);
        ForkJoinTask<Integer> res = forkJoinPool.submit(task);
        try {
            System.out.println(res.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    static class SumTask extends RecursiveTask<Integer> {
        private final int THRESHOLD = 2;
        private int start;
        private int end;

        public SumTask(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            int sum = 0;
            if (end-start<THRESHOLD) {
                for (int i = start; i < end; i++) {
                    sum += i;
                }
                return sum;
            }
            int middle = (start + end) / 2;
            SumTask task1 = new SumTask(start, middle);
            SumTask task2 = new SumTask(middle+1, end);
            task1.fork();
            task2.fork();
            Integer sum1 = task1.join();
            Integer sum2 = task2.join();
            sum = sum1 + sum2;
            return sum;
        }
    }
}
